﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TerhelesEloszto.Common;
using TerhelesEloszto.Engine;

namespace Presentation
{
	public partial class TeacherPreferences : System.Web.UI.Page
	{

		private List<ISkill> skills;
		private List<ITask> tasks;
		private ITeacher me;


		private static IEngine engine = Engine.Instance();

		protected void Page_Load( object sender, EventArgs e )
		{
			try
			{
				String visitorName = User.Identity.Name;
				if( !engine.IsTeacher( visitorName ) )
				{
					if( engine.IsAdmin( visitorName ) )
					{
						Response.Redirect( "~/Teacher/AdminProblem.aspx" );
					}
					else
					{
						Response.Redirect( "~/Problem.aspx" );
					}

				}
				else
				{
					if( !engine.IsTeacherSettingsEnabled )
					{
						Response.Redirect( "~/Teacher/NoPreferences.aspx" );
					}

					skills = engine.GetSkills();
					tasks = engine.GetTasks( true );
					me = engine.GetTeacherProfile( User.Identity.Name );

					if( !Page.IsPostBack )
					{
						for( int i = 0; i < skills.Count; i++ )
						{
							CheckBoxList1.Items.Add( skills[i].Name );
							if( me.Skills.Where( sk => sk.ID == skills[i].ID ).Any() )
							{
								CheckBoxList1.Items[i].Selected = true;
							}
						}


						foreach( ITask t in tasks ) DropDownList1.Items.Add( t.Name );
					}
				}
			}
			catch( EngineException ex )
			{
				Response.Redirect( "~/Teacher/Error.aspx" );
			}

		}

		protected void Button1_Click( object sender, EventArgs e )
		{
			try
			{
				if( !engine.IsTeacherSettingsEnabled )
				{
					Response.Redirect( "~/Teacher/Error.aspx" );
				}
				else
				{
					ITask selected = tasks[DropDownList1.SelectedIndex];
					for( int i = 0; i < skills.Count; i++ )
					{
						if( selected.RequiredSkills.Where( sk => sk.ID == skills[i].ID ).Any() )
						{
							CheckBoxList1.Items[i].Selected = true;
						}
					}
				}
			}
			catch( EngineException ex )
			{
				Response.Redirect( "~/Teacher/Error.aspx" );
			}
		}

		protected void Button2_Click( object sender, EventArgs e )
		{
			try
			{
				List<ISkill> skList = new List<ISkill>();
				for( int i = 0; i < skills.Count; i++ )
				{
					if( CheckBoxList1.Items[i].Selected )
					{
						skList.Add( skills[i] );
					}
				}
				engine.UpdatePreferences( me, skList, me.PersonalPreferences );
				Response.Redirect( "~/Teacher/PersonalPreferences.aspx" );
			}
			catch( EngineException ex )
			{
				Response.Redirect( "~/Teacher/Error.aspx" );
			}
		}
	}
}